package com.xcc.core.netty.server;


import java.math.BigInteger;
import java.net.InetSocketAddress;
import java.nio.MappedByteBuffer;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.xcc.core.netty.manager.ManagerChannel;
import com.xcc.core.netty.memery.MemeryUtils;
import com.xcc.core.netty.model.LengthModel;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.handler.timeout.IdleState;
import io.netty.handler.timeout.IdleStateEvent;

/**
 * 版权：
 * <简述>
 * <详细描述> 用户端服务器
 * @author   xcc
 * @version  $Id$
 * @since
 * @see
 */
public class ServerLengthHandler extends SimpleChannelInboundHandler<LengthModel> {
	
    private static final Log LOG = LogFactory.getLog(ServerLengthHandler.class);
	
    @Override
    public void channelActive(ChannelHandlerContext ctx)
        throws Exception {
        int   id=  new BigInteger(ctx.channel().id()
            .asShortText(), 16).intValue();
        System.out.println("内部端连接"+id);
        InetSocketAddress insocket = (InetSocketAddress)ctx.channel().remoteAddress();
        ManagerChannel.getChannelmapper().put(insocket.getAddress().getHostAddress(), id+"");
        MemeryUtils.setMap(("远程端Ip"+insocket.getAddress().getHostAddress()+":"+id+"\n").getBytes());
        LOG.info("远程端Ip"+insocket.getAddress().getHostAddress());
        ManagerChannel.getAllClient().put(id+"", ctx.channel());
        //告诉发送放客户端id
    }

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, LengthModel msg)
        throws Exception {
          switch(msg.getType()) {
          	case 1:
          		handle(ctx,msg);  //发送信息
          		break;
          	case 2:
          		LOG.info("心跳检测");
          		break;
          	case 3:
          		connect(ctx,msg);  //建立连接
          		break;
          }

    }
    
    public void connect(ChannelHandlerContext ctx, LengthModel msg) {
    	String connectId=new String(msg.getBs());
    	  Channel ch=ctx.channel();
          ManagerChannel.getChannelmapper().put(msg.getId()+"",connectId);
          System.out.println("内部系统连接成功");
    }
    
    
    public void handle(ChannelHandlerContext ctx, LengthModel msg) {
    	 	String connectId=new String(msg.getBs());
            LOG.debug(connectId);
               //外部通道
               System.out.println("发送给客户ID："+msg.getId());
               Channel ch=ManagerChannel.getClientChannel2(msg.getId()+"");
               ByteBuf buf=Unpooled.copiedBuffer(msg.getBs());
               System.out.print("3389服务发送客户端数据："); 
               for(byte b:msg.getBs()) {
                   System.out.print((0xff&b)+" ");
               }
               System.out.println();
               if(ch.isActive()) {
                   ch.writeAndFlush(buf); 
               }else {
                   System.out.println("客户端已死");
               }
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause)
        throws Exception {
        InetSocketAddress socket=(InetSocketAddress)ctx.channel().remoteAddress();
        LOG.error(socket.getAddress());
        LOG.error(cause.getMessage(),cause);
        super.exceptionCaught(ctx, cause);
    }

  

}
